"""数据库连接管理。"""

from typing import Optional
from motor.motor_asyncio import AsyncIOMotorClient, AsyncIOMotorDatabase
from .config import settings

# 全局数据库客户端
_mongodb_client: Optional[AsyncIOMotorClient] = None
_database: Optional[AsyncIOMotorDatabase] = None


async def init_database():
    """初始化数据库连接。"""
    global _mongodb_client, _database
    
    if _mongodb_client is None:
        _mongodb_client = AsyncIOMotorClient(settings.mongodb_url)
        _database = _mongodb_client[settings.mongodb_database]
    
    return _database


async def close_database():
    """关闭数据库连接。"""
    global _mongodb_client, _database
    
    if _mongodb_client is not None:
        _mongodb_client.close()
        _mongodb_client = None
        _database = None


async def get_db() -> AsyncIOMotorDatabase:
    """获取数据库实例（FastAPI依赖）。"""
    global _database

    if _database is None:
        await init_database()

    return _database


async def get_db_direct() -> AsyncIOMotorDatabase:
    """直接获取数据库实例（不需要认证）。"""
    global _database

    if _database is None:
        await init_database()

    return _database


def get_collection(collection_name: str):
    """获取集合。"""
    global _database
    
    if _database is None:
        raise RuntimeError("数据库未初始化")
    
    return _database[collection_name]